import { Component, Input, Injector, ViewChild } from '@angular/core';
import { NzDrawerRef } from 'ng-zorro-antd';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import {
  EditionEditDto,
  SubscribableEditionComboboxItemDto,
  EditionServiceProxy,
  CreateOrUpdateEditionDto,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';
@Component({
  selector: 'create-or-edit-editionDrawer',
  templateUrl: './create-or-edit-edition.component.html',
  styleUrls: ['./create-or-edit-edition.component.less'],
})
export class CreateOrEditEditionComponent extends AppComponentBase {
  @Input() id?: number;
  edittionForm: FormGroup;
  edition: EditionEditDto = new EditionEditDto();
  subscriptionVersion = 'FreeVersion';
  currency = '￥';
  isTrialActive = false;
  isWaitingDayActive = false;
  expireOperate = 'Disable';
  isAssignVersion = true;
  isLoadingBtn = false;

  constructor(
    injector: Injector,
    private drawerRef: NzDrawerRef,
    private fb: FormBuilder,
    private editionService: EditionServiceProxy,
  ) {
    super(injector);
  }

  ngOnInit() {
    this.edittionForm = this.fb.group({
      displayName: [null, [Validators.required, Validators.maxLength]],
      subscriptionVersion: [null],
      monthlyPrice: [null],
      annualPrice: [null],
      currency: [null],
      isTrialActive: [null],
      isWaitingDayActive: [null],
      trialDayCount: [null],
      waitingDayAfterExpire: [null],
      expireOperate: [null],
    });

    this.editionService.getEditionForEdit(this.id).subscribe(tenantResult => {
      this.edition = tenantResult.edition;
      this.isTrialActive = this.edition.trialDayCount != null;
      this.isWaitingDayActive = this.edition.waitingDayAfterExpire != null;
      if (this.edition != null) {
        this.isAssignVersion = false;
        this.expireOperate = 'AssignVersion';
        if (
          this.edition.monthlyPrice !== null ||
          this.edition.annualPrice !== null
        ) {
          this.subscriptionVersion = 'ChargedVersion';
        }
      }
    });
  }


  expireOperateFocus() {
    this.isAssignVersion = !this.isAssignVersion;
  }

  selectedEditionChange(edition: SubscribableEditionComboboxItemDto) {
    if (edition != null) {
      this.edition.expiringEditionId = +edition.value;
    }
  }

  close(): void {
    this.drawerRef.close(false);
  }

  submitForm(): void {
    for (const i in this.edittionForm.controls) {
      this.edittionForm.controls[i].markAsDirty();
      this.edittionForm.controls[i].updateValueAndValidity();
    }
    if (this.edittionForm.valid) {
      this.isLoadingBtn = true;
      const input = new CreateOrUpdateEditionDto();
      input.edition = this.edition;
      this.editionService.createOrUpdateEdition(input).subscribe(result => {
        this.isLoadingBtn = false;
        this.notify.success('操作成功！');
        this.drawerRef.close(true);
      });
    }
  }
}
